/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.web.book.front;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.boxin.framework.base.utils.DateUtils;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.entity.book.BookOrder;
import com.boxin.ims.modules.wechat.entity.book.BookOrderRecord;
import com.boxin.ims.modules.wechat.entity.dic.TimeQuantum;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.boxin.ims.modules.wechat.service.book.BookOrderRecordService;
import com.boxin.ims.modules.wechat.service.book.BookOrderService;
import com.boxin.ims.modules.wechat.service.dic.TimeQuantumService;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 预定服务客户端服务处理器
 * @author Jakemanse
 * @version 2013-12-08
 */
@Controller
@RequestMapping(value = Global.FRONT_PATH+"/wechat/book/bookOrder")
public class BookOrderFrontController extends BaseController {

	@Autowired
	private BookOrderRecordService bookOrderRecordService;
	
	@Autowired
	private BookOrderService bookOrderService;
	
	@Autowired
	private TimeQuantumService timeQuantumService;
	
	@Autowired
	private WechatMemberService wechatMemberService;
	
	@Autowired
	private WechatDaoHelper wechatDaoHelper;
	
	private Logger logger = Logger.getLogger(BookOrderFrontController.class);
	
	
	@RequestMapping(value = {"list", ""})
	public String list(BookOrderRecord bookOrderRecord, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			bookOrderRecord.setUser(user);
		}
        Page<BookOrderRecord> page = bookOrderRecordService.find(new Page<BookOrderRecord>(request, response), bookOrderRecord); 
        model.addAttribute("page", page);
		return "modules/wechat/book/bookOrderRecordList";
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-12-27  下午10:13:48
	 * @function <p> 店的所有预定列表 </p>
	 * @param bookOrderRecord
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "bookIndex")
	public String bookIndex(  HttpServletRequest request, HttpServletResponse response, Model model) {
		
		String uid = request.getParameter("uid");	//user Id
		String wechatId =  request.getParameter("wechatId");
		String storeId = request.getParameter("storeId");
		
		 List<BookOrder>  bookOrderList = 	bookOrderService.findByStorefrontId(Long.parseLong(storeId));
		
		model.addAttribute("bookOrderList", bookOrderList);
		model.addAttribute("uid", uid);
		model.addAttribute("wechatId", wechatId);
		
		return "modules/wechat/front/book/bookIndex";
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-12-28  下午3:34:56
	 * @function <p> 预订项页面 </p>
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "bookItems")
	public String bookItems(  HttpServletRequest request, HttpServletResponse response, Model model) {
		
		String uid = request.getParameter("uid");	//user Id
		String wechatId =  request.getParameter("wechatId");
		String storeId = request.getParameter("storeId");
		String bookOrderId = request.getParameter("boid");
		
		BookOrder  bookOrder  = 	bookOrderService.get(Long.parseLong(bookOrderId));
		Map<String,String> params = new HashMap<String, String>();
		params.put("userId", uid);
		List<Map<String,Object>> timeList = wechatDaoHelper.findFreeTimequantum(params);
		model.addAttribute("bookOrder", bookOrder);
		model.addAttribute("uid", uid);
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("timeList", timeList);
		
		return "modules/wechat/front/book/bookItems";
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-12-27  下午10:28:57
	 * @function <p> 生成预订订单 </p>
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "dobook")
	public String dobook(  HttpServletRequest request, HttpServletResponse response, Model model) {
		
		String uid = request.getParameter("uid");	//user Id
		String tid = request.getParameter("timeId");	//时间段
		String wechatId =  request.getParameter("wechatId");
		String storeId = request.getParameter("storeId");
		String bookOrderId = request.getParameter("boid");
		
		Map<String, String> resultMap = Maps.newHashMap();
		try {
			
			User user = UserUtils.getUserById(Long.parseLong(uid));
			BookOrder bookOrder = bookOrderService.get(Long.parseLong(bookOrderId));
			TimeQuantum timeQuantum = timeQuantumService.get(Long.parseLong(tid));
			WechatMember member = wechatMemberService.getByWechatMemberId(user, wechatId);
			
			BookOrderRecord record = new BookOrderRecord();
			record.setBookOrder(bookOrder);
			record.setTimeQuantum(timeQuantum);
			record.setDay(DateUtils.getTodayString());
			record.setUser(user);
			record.setMember(member);
			record.setMobile(member.getMobile());
			record.setStoreName(bookOrder.getStorefront().getName());
			record.setStatus(BookOrder.STATUS_ORDER);
			record.setName(bookOrder.getName()+"-"+timeQuantum.getName());
			
			bookOrderRecordService.save(record);	//保存
			
			resultMap.put("result", "ok");
			resultMap.put("message", "预订成功.");
			
		} catch (Exception e) {
			resultMap.put("result", "error");
			e.printStackTrace();
			
		}
		
		writeJson(request, response, resultMap);
		
		
		return null;
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-12-27  下午10:28:57
	 * @function <p> 生成预订订单  无选择时间段 </p>
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "doNotimebook")
	public String doNotimebook(  HttpServletRequest request, HttpServletResponse response, Model model) {
		
		String uid = request.getParameter("uid");	//user Id
		String wechatId =  request.getParameter("wechatId");
		String bookOrderId = request.getParameter("boid");
		String message = request.getParameter("message");
		
		
		Map<String, String> resultMap = Maps.newHashMap();
		try {
			
			User user = UserUtils.getUserById(Long.parseLong(uid));
			BookOrder bookOrder = bookOrderService.get(Long.parseLong(bookOrderId));
			WechatMember member = wechatMemberService.getByWechatMemberId(user, wechatId);
			
			BookOrderRecord record = new BookOrderRecord();
			record.setBookOrder(bookOrder);
			record.setDay(DateUtils.getTodayString());
			record.setUser(user);
			record.setMember(member);
			record.setMobile(member.getMobile());
			record.setStoreName(bookOrder.getStorefront().getName());
			record.setStatus(BookOrder.STATUS_ORDER);
			record.setRemarks(message);
			record.setProcessFlag(BookOrderRecord.NO);
			record.setTerminal(bookOrder.getStorefront().getTerminal());
			record.setName(bookOrder.getName());
			
			bookOrderRecordService.save(record);	//保存
			
			resultMap.put("result", "ok");
			resultMap.put("message", "预订成功.");
			
		} catch (Exception e) {
			resultMap.put("result", "error");
			e.printStackTrace();
			
		}
		
		writeJson(request, response, resultMap);
		
		
		return null;
	}
	
	


	
	/**
	 * @author Jakemanse
	 * @time 2013-12-16  下午3:20:25
	 * @function <p>查询预定  </p>
	 */
	@RequestMapping(value = "query"  )
	public void queryBookOrder( HttpServletRequest request, HttpServletResponse response, Model model){
		String storeId =	request.getParameter("storeId");	//所属分店
		String status  =	request.getParameter("status");	//状态
		
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-12-16  下午3:25:51
	 * @function <p> 查询所有店面 </p>
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value =  "stores"  )
	public void queryStorefronts( HttpServletRequest request, HttpServletResponse response, Model model){
		String uid =	request.getParameter("uid");	//所属分店
		
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-12-30  上午12:02:16
	 * @function <p> 查询预订记录  </p>
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value =  "queryBookOrderRecord"  )
	public void queryBookOrderRecord(HttpServletRequest request, HttpServletResponse response, Model model){
		
		String mobile = request.getParameter("mobile");
		String day = request.getParameter("day");
		String uid = request.getParameter("uid");		// userId
		String tid = request.getParameter("tid");		//terminal Id
		Map<String, String> params = Maps.newHashMap();
		if(!StringUtils.isEmpty(mobile)){
			params.put("mobile", mobile);
		}
		if(StringUtils.isEmpty(day)){
			day = DateUtils.getTodayString();
		}
		params.put("day", day);
		params.put("userId", uid);
		params.put("tid", tid);
		
		
		List<Map<String,Object>> resultList = 	wechatDaoHelper.findBookOrderRecord(params);
		String xml = "";
		if(resultList!=null && !resultList.isEmpty()){
			xml = wrapXML(true,"","",resultList);
		}else{
			xml = wrapXML(false,"未找预订的记录","",resultList);
		}
		
		responseXML(request, response, xml);
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-12-30  上午12:02:16
	 * @function <p> 处理预订记录  </p>
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value =  "processBookOrderRecord"  )
	private void processBookOrderRecord(HttpServletRequest request, HttpServletResponse response, Model model){
		String id = request.getParameter("id");
		String reply =  request.getParameter("reply");
		
		Map<String, String> params = Maps.newHashMap();
		params.put("id", id);
		params.put("reply", reply);
		params.put("processFlag", "1");
		wechatDaoHelper.updateBookOrderRecord(params);
		
		
	}
	
	
	private String wrapXML(boolean success,String errorInfo,String tip,List<Map<String,Object>> resultMapList ){
		
		StringBuffer xml = new StringBuffer();
		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		xml.append("<response>");
		xml.append("<success>").append(success).append("</success>");
		
		if(resultMapList!=null  && !resultMapList.isEmpty()){
			xml.append("<BookOrderRecords>");	
			for(Map<String,Object> resultMap : resultMapList){
				xml.append("<BookOrderRecord>");	
				if(resultMap.get("id") != null){
					xml.append("<id>").append(resultMap.get("id")).append("</id>");			//奖品名称
				}
				if(resultMap.get("name") != null){
					xml.append("<name>").append(resultMap.get("name")).append("</name>");			//奖品名称
				}
				
				if(resultMap.get("mobile") != null){
					xml.append("<mobile>").append(resultMap.get("mobile")).append("</mobile>");			//奖品名称
				}
				
				if(resultMap.get("member_name") != null){
					xml.append("<memberName>").append(resultMap.get("member_name")).append("</memberName>");			//奖品名称
				}
				if(resultMap.get("process_flag") != null){
					xml.append("<processFlag>").append(resultMap.get("process_flag")).append("</processFlag>");			//奖品名称
				}
				
				if(resultMap.get("remarks") != null){
					xml.append("<remarks>").append(resultMap.get("remarks")).append("</remarks>");			//奖品名称
				}
				
				if(resultMap.get("create_time") != null){
					xml.append("<createTime>").append(resultMap.get("create_time")).append("</createTime>");			//创建时间
				}
				
				
				xml.append("</BookOrderRecord>");
			}
			xml.append("</BookOrderRecords>");
			
		}
		
		
		xml.append("<errorInfo>").append(errorInfo).append("</errorInfo>");
		xml.append("<tip>").append(tip).append("</tip>");
		xml.append("</response>");
		logger.debug(xml.toString());
		return xml.toString();
		
	}
	
	
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-12-16  下午3:33:58
	 * @function <p> 返回查询分店名称  XML </p>
	 * @param success
	 * @param errorInfo
	 * @param tip
	 * @param resultMapList
	 * @return
	 */
	private String wrapQueryStoreXML(boolean success,String errorInfo,String tip,List<Map<String,Object>> resultMapList ){
		
		StringBuffer xml = new StringBuffer();
		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		xml.append("<response>");
		xml.append("<success>").append(success).append("</success>");
		
		
		if(resultMapList!=null && !resultMapList.isEmpty()){
			for(Map<String,Object> map : resultMapList){
				
				if(map.get("id") != null){
					xml.append("<id>").append(map.get("id")).append("</id>");			//奖品名称
				}
				if(map.get("name") != null){
					xml.append("<name>").append(map.get("name")).append("</name>");			//奖品名称
				}
				
				if(map.get("address") != null){
					xml.append("<address>").append(map.get("address")).append("</address>");			//奖品名称
				}
				
			}
		}
		
		xml.append("<errorInfo>").append(errorInfo).append("</errorInfo>");
		xml.append("<tip>").append(tip).append("</tip>");
		xml.append("</response>");
		logger.debug(xml.toString());
		return xml.toString();
		
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-12-16  下午3:35:28
	 * @function <p> 预定查询  </p>
	 * @param success
	 * @param errorInfo
	 * @param tip
	 * @param resultMapList
	 * @return
	 */
	private String wrapQueryBookOrderXML(boolean success,String errorInfo,String tip,List<Map<String,Object>> resultMapList ){
		
		StringBuffer xml = new StringBuffer();
		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		xml.append("<response>");
		xml.append("<success>").append(success).append("</success>");
		
			
		if(resultMapList!=null && !resultMapList.isEmpty()){
			for(Map<String,Object> map : resultMapList){
				
				if(map.get("id") != null){
					xml.append("<id>").append(map.get("id")).append("</id>");			//奖品名称
				}
				if(map.get("name") != null){
					xml.append("<name>").append(map.get("name")).append("</name>");			//奖品名称
				}
				
				if(map.get("address") != null){
					xml.append("<address>").append(map.get("address")).append("</address>");			//奖品名称
				}
				
			}
		}
		
		xml.append("<errorInfo>").append(errorInfo).append("</errorInfo>");
		xml.append("<tip>").append(tip).append("</tip>");
		xml.append("</response>");
		logger.debug(xml.toString());
		return xml.toString();
		
	}
	
	
	
	

}
